﻿<%@ WebHandler Language="C#" Class="mp" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Security;
using System.Net;
using System.Collections;
using System.Security.Cryptography;

public class mp : IHttpHandler
{
    private string[] OpenParameters = { "signature", "timestamp", "nonce", "echostr" };



    public void ProcessRequest(HttpContext context)
    {
        bool isLanding = true;
        foreach (string s in OpenParameters)
        {
            if (!context.Request.QueryString.AllKeys.Contains(s))
                isLanding = false;

        }

        if (isLanding && checkSignature(context.Request.QueryString["signature"], context.Request.QueryString["timestamp"], context.Request.QueryString["nonce"], "20151224rgf"))
        {
            context.Response.ContentType = "text/plain";
            string echoString = context.Request.QueryString["echostr"];
            context.Response.Write(echoString);
        }
        else//接收消息 明文格式
        {
            XmlDocument xmlData = new XmlDocument();
            xmlData.Load(context.Request.InputStream);
            WxText.wxLog(WxText.ConvertXmlToString(xmlData));

            #region 普通文本信息用
            string Content = "";
            string MsgId = "";
            string msg = "";
            #endregion

            #region 事件信息用
            string Event = "";
            string EventKey = "";
            #endregion


            string ToUserName = xmlData.FirstChild["ToUserName"].InnerText;
            string FromUserName = xmlData.FirstChild["FromUserName"].InnerText;
            string CreateTime = xmlData.FirstChild["CreateTime"].InnerText;
            string MsgType = xmlData.FirstChild["MsgType"].InnerText;
            string re_userbh = "";

            if (MsgType == "event")
            {

                Event = xmlData.FirstChild["Event"].InnerText;


                if (Event == "subscribe")
                {
                    EventKey = xmlData.FirstChild["EventKey"].InnerText;
                    re_userbh = EventKey.Replace("qrscene_", "");
                    InsertWxMember(FromUserName, re_userbh, "关注");
                    Content = "感谢您关注雪燃淳，请<a href=\"http://?f=" + FromUserName + "&s=" + EventKey.Replace("qrscene_", "") + "\">点击此处</a>或者使用下方菜单“完善信息”来完善您的会员信息。";
                    msg = createResponseMsg(ToUserName, FromUserName, Content);
                }
                else if (Event == "SCAN")
                {
                    EventKey = xmlData.FirstChild["EventKey"].InnerText;
                    re_userbh = EventKey.Replace("qrscene_", "");
                    InsertWxMember(FromUserName, re_userbh, "扫码");
                    Content = "您可以<a href=\"http://?完善信息f=" + FromUserName + "&s=" + EventKey + "\">点击此处</a>完善您的信息，也可以使用下方菜单中的“完善信息”来完善您的会员信息";
                    msg = createResponseMsg(ToUserName, FromUserName, Content);
                }
                else if (Event == "merchant_order")
                {

                    string orderid = xmlData.FirstChild["OrderId"].InnerText;
                    
                    InserWxOrder(orderid);
                }

                else if (Event == "unsubscribe")
                {
                    return;
                }
                msg = createResponseMsg(ToUserName, FromUserName, Content);

                context.Response.ContentType = "text/plain";
                context.Response.Write(msg);
            }
            else if (MsgType == "text")
            {
                Content = "感谢您关注";
                MsgId = xmlData.FirstChild["MsgId"].InnerText;
                msg = createResponseMsg(ToUserName, FromUserName, Content);

                context.Response.ContentType = "text/plain";
                context.Response.Write(msg);
            }



        }


    }

    public void InsertWxMember(string user_openid, string recommend_userbh, string sign)
    {
        string sql = "";
        DBHelper d = new DBHelper();
        int i = d.getCount("wx_member", "user_openid='" + user_openid + "'");

        if (i == 0)
        {
            sql = "insert into wx_member(user_openid,recommend_userbh,sign) values('" + user_openid + "','" + recommend_userbh + "',N'" + sign + "')";
            d.executeNoneQuery(sql);
        }
    }

    public void InserWxOrder(string order_id)
    {
        DBHelper d = new DBHelper();
        string buyer_openid = "";
        string order_status = "";
        string product_name = "";
        string product_price = "";
        string product_count = "";
        string order_total_price = "";

        Ticket.GetOrder(order_id, ref buyer_openid, ref order_status, ref product_name, ref product_price, ref product_count, ref order_total_price);


        if (order_status == "2" || order_status == "3" || order_status == "5")
        {
            int i = d.getCount("wx_order", "order_id='" + order_id + "'");
            if (i == 0)
            {
                string sql = "insert into wx_order(order_id,buyer_openid,product_name,product_price,product_count,order_total_price,order_status) values('" + order_id + "','" + buyer_openid + "',N'" + product_name + "','" + product_price + "','" + product_count + "','" + order_total_price + "','" + order_status + "')";
                d.executeNoneQuery(sql);
            }
        }
    }











    //将接受的文本 以文本消息方式返回
    public string createResponseMsg(string FromUserName, string ToUserName, string msg)
    {
        string xmldata = "<xml><ToUserName><![CDATA[" + ToUserName + "]]></ToUserName><FromUserName><![CDATA[" + FromUserName + "]]></FromUserName><CreateTime>" + DateTime.Now.Ticks + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msg + "]]></Content></xml>";

        return xmldata;
    }

    private bool verify(string signature, string timestamp, string nonce)
    {
        //校验签名
        return true;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    private bool checkSignature(string signature, string timestamp, string nonce, string token)
    {
        ArrayList tmpArray = new ArrayList();
        tmpArray.Add(token);
        tmpArray.Add(timestamp);
        tmpArray.Add(nonce);
        tmpArray.Sort();
        string tmpStr = (string)tmpArray[0] + (string)tmpArray[1] + (string)tmpArray[2];

        //建立SHA1对象
        SHA1 sha = new SHA1CryptoServiceProvider();

        //将mystr转换成byte[]
        ASCIIEncoding enc = new ASCIIEncoding();
        byte[] dataToHash = enc.GetBytes(tmpStr);

        //Hash运算
        byte[] dataHashed = sha.ComputeHash(dataToHash);

        //将运算结果转换成string
        string hash = BitConverter.ToString(dataHashed).Replace("-", "");


        if (hash.ToLower() == signature.ToLower())
            return true;
        else
            return false;

    }

}